// Load required modules
var https   = require("http");     // https server core module
var fs      = require("fs");        // file system core module
var express = require("express");   // web framework external module
var io      = require("socket.io"); // web socket external module

// This sample is using the easyrtc from parent folder.
// To use this server_example folder only without parent folder:
// 1. you need to replace this "require("../");" by "require("easyrtc");"
// 2. install easyrtc (npm i easyrtc --save) in server_example/package.json

var easyrtc = require("easyrtc"); // EasyRTC internal module

// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var httpApp = express();
httpApp.use(express.static(__dirname + "/public/"));
// Start Express https server on port 8443
var webServer = https.createServer(httpApp);
// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer, {"log level":1});
// Start EasyRTC server
var rtc = easyrtc.listen(httpApp, socketServer);
// Listen on port 8443
webServer.listen(8443, function () {
    console.log('listening on https://localhost:8443');
});




var list = {}
var roomNum = 0
socketServer.on('connection',function(socket){
	console.log('cc')
	socket.on('join',function(data){
		console.log(data)
		list[data] = {
			io:socket,//用户的sokcet
			roomStatus:false,//是否加入房间
		}
		
	})
	/*socket.on('joinRoom',function(data){
		list[data] = {
			io:socket,//用户的sokcet
			roomStatus:true,//是否加入房间
			
		}
	})*/
	socket.on('call',function(data){
		roomNum++
		let names = JSON.parse(data.all)
		let caller = data.caller
		var peoples = [caller].concat(names)
		var room = []
		names.forEach(function(val,index){
			if(list.hasOwnProperty(val)==false){
			socket.emit('fail',val)
		}else if(list[val].roomStatus){
			socket.emit('failRoom',val)
		}else{
			room.push(val)
			list[val].io.emit('subcall',{caller:caller,accepter:val,all:peoples,room:room,roomNum:roomNum})	
		}
		})	
	})
	
	socket.on('accept',function(data){
		console.log(data.roomNum)
		list[data.accepter].roomStatus = true
		list[data.caller].roomStatus = true			
		list[data.accepter].io.emit('showvd',data)
		setTimeout(function(){
			list[data.caller].io.emit('showvd',data)
		},1000)	
	})
	
	socket.on('refuse',function(data){
		console.log('refuse')
		list[data.accepter].roomStatus = false
		list[data.caller].io.emit('anserRefuse',data)
	})
	socket.on('play',function(data){	
		data.all.all.forEach(function(val,index){
			list[val].emit('stPlay',data)
		})
	})
})
socketServer.on('disconnection',function(socket){
})
